
	var qrUrl = "https://www.fuskey.com/servlet/QRServlet";
    var fuskeyUrl = "http://localhost:8080/app/";
    //var qrUrl = "http://localhost:8080/app/servlet/QRServlet";
		
	function bindDeleteTextAction(){
		$(".delete-textbox").click(function() {
			var id = $(this).parent().children(":first").attr("text-no");
			$(this).parent().remove();
			$('#txt_div_' + id).remove();
		});
	}
	function bindToggleTextAction(){
		$(".toggle-textbox").click(function() {
			var id = $(this).parent().children(":first").attr("text-no");
			var visible =  $(this).parent().children(":first").attr('visible')=='true';
			var editable = $(this).parent().children(":first").attr('editable')=='true';
			if (visible){
				$(this).parent().children(":first").prop('disabled', true);
				$(this).parent().children(":first").attr('visible','false');
				$('#txt_div_' + id).hide();
				$(this).html("<i class='icon-white icon-eye-open'></i>");
				$(this).removeClass("red").addClass("green");
				toggleText(id, 0);
			}
			else{
				if (editable)
					$(this).parent().children(":first").prop('disabled', false);
				$(this).parent().children(":first").attr('visible','true');
				$('#txt_div_' + id).show();
				$(this).html("<i class='icon-white icon-eye-close'></i>");
				$(this).removeClass("green").addClass("red");
				toggleText(id, 1);
			}
		});
	}
	function getNextTextNumber(){
		var max = 0;
		$(".input-txt").each( function() {
			var num = parseInt($(this).attr("text-no"));
			max = Math.max(max,num);
		});
		return max+1;
		
	}
	function getNextIconNumber(){
		var max = 0;
		$(".picon").each( function() {
			var num = parseInt($(this).attr("icon-no"));
			max = Math.max(max,num);
		});
		return max+1;
		
	}
	function selectText(id){
		$(".selected-element").each(function() {
			$(this).removeClass("selected-element").removeClass("hovered-element").addClass("default-element");
		});
		$(".input-txt").each(function() {
			$(this).removeClass("selected-text");
		});
		$("div#txt_div_" + id).removeClass("default-element").removeClass("hovered-element").addClass("selected-element");
		$("textarea#input-txt-" + id).addClass("selected-text").focus();
		setTextControls(id);
		switchToTextTab();		
	}
	function generateTextParams(){
		var params = "&font=" + $('select#font-select').val(); 
		params += "&size=" + $('select#font-size-select').val(); 
		params += "&color=" + rgb2hex($('div#colorSelector').css('background-color')); 
		params += "&bold=" + ($('button#btnBold').hasClass('active')?"true":"false");
		params += "&italic=" + ($('button#btnItalic').hasClass('active')?"true":"false");
		params += "&underline=" + ($('button#btnUnderline').hasClass('active')?"true":"false");
		params += "&align=" + ($('button#btnAlignRight').hasClass('active')?"2":($('button#btnAlignCenter').hasClass('active')?"1":"0"));
		return params;
	}
	function generateInitialTextParams(font,size,color,bold,italic,underline,align){
		var params = "&font=" + font; 
		params += "&size=" + size; 
		params += "&color=" + color; 
		params += "&bold=" + (bold==1?"true":"false");
		params += "&italic=" + (italic==1?"true":"false");
		params += "&underline=" + (underline==1?"true":"false");
		params += "&align=" + align;
		return params;
	}
    function hex(x) {
        return ("0" + parseInt(x).toString(16)).slice(-2);
    }
	function rgb2hex(rgb) {
	    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
	    return hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
	}

	function selectedTextDivNo(){
		var id = "-1";
		$('div.txt').each(function(){
			if ($(this).hasClass('selected-element')){
				id = $(this).attr('text-no');
			}
		});
		return id;
	}
	function updateSelectedText(){
		var id = selectedTextDivNo();
		var text = $("textarea#input-txt-" + id).val();
		editText(text, id);
	}

	function getTextControlParams(){
		var params = "text-font='" + $('select#font-select').val()+"'"; 
		params += " text-size='" + $('select#font-size-select').val()+"'"; 
		params += " text-color='" + rgb2hex($('div#colorSelector').css('background-color'))+"'";  
		params += " text-bold='" + ($('button#btnBold').hasClass('active')?"true":"false")+"'"; 
		params += " text-italic='" + ($('button#btnItalic').hasClass('active')?"true":"false")+"'"; 
		params += " text-underline='" + ($('button#btnUnderline').hasClass('active')?"true":"false")+"'"; 
		params += " text-align='" + ($('button#btnAlignRight').hasClass('active')?"2":($('button#btnAlignCenter').hasClass('active')?"1":"0"))+"'"; 
		params += " text-align='" + ($('button#btnAlignRight').hasClass('active')?"2":($('button#btnAlignCenter').hasClass('active')?"1":"0"))+"'"; 
		params += " element-id='-1'"; 
		return params;
	}
	
	function getInitialTextControlParams(font,size,color,bold,italic,underline,align,top,left,elemendId){
		var params = "text-font='" + font+"'"; 
		params += " text-size='" + size+"'"; 
		params += " text-color='" + color +"'";  
		params += " text-bold='" + (bold==1?"true":"false") +"'"; 
		params += " text-italic='" + (italic==1?"true":"false") +"'"; 
		params += " text-underline='" + (underline==1?"true":"false") +"'"; 
		params += " text-align='" + align +"'"; 
		params += " text-top='" + top +"'"; 
		params += " text-left='" + left +"'"; 
		params += " element-id='" + elemendId +"'"; 
		return params;
	}
	function setTextControlParams(id){
		$("textarea#input-txt-" + id).attr('text-font',$('select#font-select').val()); 
		$("textarea#input-txt-" + id).attr('text-size',$('select#font-size-select').val()); 
		$("textarea#input-txt-" + id).attr('text-color',rgb2hex($('div#colorSelector').css('background-color')));  
		$("textarea#input-txt-" + id).attr('text-bold',($('button#btnBold').hasClass('active')?"true":"false")); 
		$("textarea#input-txt-" + id).attr('text-italic',($('button#btnItalic').hasClass('active')?"true":"false")); 
		$("textarea#input-txt-" + id).attr('text-underline',($('button#btnUnderline').hasClass('active')?"true":"false")); 
		$("textarea#input-txt-" + id).attr('text-align',($('button#btnAlignRight').hasClass('active')?"2":($('button#btnAlignCenter').hasClass('active')?"1":"0"))); 
	}

	function setTextControls(id){
		$('select#font-select').val($("textarea#input-txt-" + id).attr("text-font"));
		$('select#font-size-select').val($("textarea#input-txt-" + id).attr("text-size"));
		$('div#colorSelector').css('backgroundColor','#' + $("textarea#input-txt-" + id).attr("text-color")).ColorPickerSetColor('#' + $("textarea#input-txt-" + id).attr("text-color"));
		if ($("textarea#input-txt-" + id).attr("text-bold") == "true" && !$('button#btnBold').hasClass('active'))
			$('button#btnBold').addClass('active');
		if ($("textarea#input-txt-" + id).attr("text-bold") == "false" && $('button#btnBold').hasClass('active'))
			$('button#btnBold').removeClass('active');
		if ($("textarea#input-txt-" + id).attr("text-italic") == "true" && !$('button#btnItalic').hasClass('active'))
			$('button#btnItalic').addClass('active');
		if ($("textarea#input-txt-" + id).attr("text-italic") == "false" && $('button#btnItalic').hasClass('active'))
			$('button#btnItalic').removeClass('active');
		if ($("textarea#input-txt-" + id).attr("text-underline") == "true" && !$('button#btnUnderline').hasClass('active'))
			$('button#btnUnderline').addClass('active');
		if ($("textarea#input-txt-" + id).attr("text-underline") == "false" && $('button#btnUnderline').hasClass('active'))
			$('button#btnUnderline').removeClass('active');
		if ($("textarea#input-txt-" + id).attr("text-align") == "2"){
			$('button#btnAlignLeft').removeClass('active');
			$('button#btnAlignCenter').removeClass('active');
			$('button#btnAlignRight').addClass('active');
		}
		else if ($("textarea#input-txt-" + id).attr("text-align") == "1"){
			$('button#btnAlignLeft').removeClass('active');
			$('button#btnAlignCenter').addClass('active');
			$('button#btnAlignRight').removeClass('active');
		}
		else {
			$('button#btnAlignLeft').addClass('active');
			$('button#btnAlignCenter').removeClass('active');
			$('button#btnAlignRight').removeClass('active');
		}
	}

	function addQRCode(qrId, width,height,data,top,left,qrmoving,rotation){
		$(".qrcode").attr("data-rotate",""+rotation).html("<img src='"+qrUrl+"?width="+width+"&height="+height+"&data="+encodeURIComponent(data)+"' alt='QR code'>"); 
		$("<div class='img-del-handler'><i class='icon-repeat'></i></div>").appendTo($(".qrcode"));
		$(".qrcode").attr("element-id",qrId); 
		$(".qrcode").attr("qr-code",data); 
		$(".qrcode > img").rotate(rotation);
		$(".qrcode").css("top",top+"px").css("left",left+"px");
		$(".qrcode").hover(function(e) {
			$(this).find(".img-del-handler").each(function(){$(this).show();})
		}, function() {
			$(this).find(".img-del-handler").each(function(){$(this).hide();})
		});	
		$(".qrcode > .img-del-handler").click(function(){
			var rot = (parseInt($(".qrcode").attr("data-rotate"))+15) % 360;
			$(".qrcode").attr("data-rotate",rot+"");
			$(".qrcode > img").rotate(rot);
			saveQRCode(qrId, $(".qrcode").attr("qr-code"));
		});
		if (qrmoving == 1){
			$(".qrcode[element-id="+qrId+"]").draggable( {
				"containment" :"parent"
			});
			$(".qrcode[element-id="+qrId+"]").bind("dragstop",function() {
				saveQRCode(qrId, $(".qrcode").attr("qr-code"));
	  		});
		}
		$(".qrcode[element-id="+qrId+"]").resizable({
		      aspectRatio: 1,
		      handles: 'se',
		      autoHide: true,
		      maxHeight: 200,
		      maxWidth: 200,
		      minHeight: 50,
		      minWidth: 50
		});
		$(".qrcode[element-id="+qrId+"]").on( "resizestop", function( event, ui ) {
			changeQRCode($(".qrcode").attr("qr-code"));
			saveQRCode(qrId, $(".qrcode").attr("qr-code"));
		});
	}
	function changeQRCode(data){ 
		$(".qrcode img").attr("src",qrUrl+"?width="+$(".qrcode").css("width").replace("px","")+"&height="+$(".qrcode").css("height").replace("px","")+"&data="+encodeURIComponent(data)); 
		$(".qrcode").attr("qr-code",data); 
	}
	function addQRCodeInline(width,height,data){
		$(".qrcode-inline").html("<img src='"+qrUrl+"?width="+width+"&height="+height+"&data="+encodeURIComponent(data)+"' alt='QR code'>"); 
	}

	function switchToTextTab(){
		$('#cardtab li:eq(0) a').tab('show'); 	
	}
	function switchToImageTab(){
		$('#cardtab li:eq(1) a').tab('show'); 	
	}
	
	if (typeof String.prototype.startsWith != 'function') {
		  // see below for better implementation!
		  String.prototype.startsWith = function (str){
		    return this.indexOf(str) == 0;
		  };
	}
	
	function createExistingImage(pImageId,cardId,top,left,width,height,src,elementId){
		if (pImageId == 0){
			$('<div class="img-holder"  pimg-id="0"><img src="../'+src+'" class="img-polaroid" pimg-id="0"></div>').appendTo($("#cardtab-pane2 > div"));
		}
		var img = $('img[pimg-id="'+pImageId+'"]');
		$("<div id='img_div_" + pImageId + "' class='picture default-element' pimg-id='"+pImageId+"' style='z-index:" + 1 + ";'><img class='dynamic' src='../"+src+"' pimg-id='"+pImageId+"' element-id='"+elementId+"'><div class='img-del-handler'><i class='icon-remove'></i></div><div>").appendTo($("#editable-area"));
		$('#img_div_' + pImageId).css({"top":top+"px","left":left+"px"});
		
		$('#img_div_' + pImageId).draggable( {
			"containment" :"parent"		
		});
		var cardImg = $('#img_div_' + pImageId).children(":first");
		cardImg.css({"width":width+"px","height":height+"px"});
		cardImg.resizable({
		      aspectRatio: cardImg.css("width").replace("px","")/cardImg.css("height").replace("px",""),
		      handles: 'se',
		      autoHide: true,
		      maxHeight: $("#editable-area").css("height").replace("px",""),
		      maxWidth: $("#editable-area").css("width").replace("px","")
	    });
		$("#img_div_" + pImageId).hover(function(e) {
			$(this).find(".img-del-handler").each(function(){$(this).show();})
		}, function() {
			$(this).find(".img-del-handler").each(function(){$(this).hide();})
		});		
		$("#img_div_" + pImageId +" > .img-del-handler").click(function(){
			deleteImage(pImageId,cardId);
		});
		$(".img-holder[pimg-id='"+pImageId+"']").addClass("active");
		$('#img_div_' + pImageId ).children(":first").on( "resizestop", function( event, ui ) {
			saveImage(pImageId,cardId,elementId);
		});
		$('#img_div_' + pImageId).on( "dragstop", function( event, ui ) {
			saveImage(pImageId,cardId,elementId);
		});
	}

	function createImage(pImageId,cardId){
		var img = $('img[pimg-id="'+pImageId+'"]');
		$("<div id='img_div_" + pImageId + "' class='picture default-element' pimg-id='"+pImageId+"' style='z-index:" + 1 + ";'><img class='dynamic' src='' pimg-id='"+pImageId+"'><div class='img-del-handler'><i class='icon-remove'></i></div><div>").appendTo($("#editable-area"));
		$('#img_div_' + pImageId).draggable( {
			"containment" :"parent"		
		});
		$("div#img_div_" + pImageId + " > img").on("load",function(){
			var cardImg = $('#img_div_' + pImageId).children(":first");
			cardImg.resizable({
			      aspectRatio: cardImg.css("width").replace("px","")/cardImg.css("height").replace("px",""),
			      handles: 'se',
			      autoHide: true,
			      maxHeight: $("#editable-area").css("height").replace("px",""),
			      maxWidth: $("#editable-area").css("width").replace("px","")
		    });
			$("#img_div_" + pImageId).hover(function(e) {
				$(this).find(".img-del-handler").each(function(){$(this).show();})
			}, function() {
				$(this).find(".img-del-handler").each(function(){$(this).hide();})
			});		
			$("#img_div_" + pImageId +" > .img-del-handler").click(function(){
				deleteImage(pImageId,cardId);
			});
			saveImage(pImageId,cardId,"-1");
		});
		$("div#img_div_" + pImageId + " > img").attr("src",img.attr("src"));
	}
	
	function saveImage(pImageId,cardId,elementId){
		console.log("save started for pImageId:" + pImageId);
		var el = $('#img_div_' + pImageId).children(":first").children(":first");
		var params = "";
		params += "pimgId=" + pImageId;
		params += "&h=" + el.height();
		params += "&w=" + el.width();
		params += "&top=" + el.parent().parent().position().top;
		params += "&left=" + el.parent().parent().position().left;
		params += "&elementId=" + elementId;
		params += "&cardId=" + cardId;
		
		$.getJSON("card/processSaveImage.jsp?"+params, function(data){
			var items = [];
			  $.each(data, function(key, val) {
				  if (key == "element-id" &&  val!="-1"){ 
					  el.attr(key,val);
					  if (elementId == "-1"){
							$('#img_div_' + pImageId ).children(":first").on( "resizestop", function( event, ui ) {
								saveImage(pImageId,cardId,val);
							});
							$('#img_div_' + pImageId).on( "dragstop", function( event, ui ) {
								saveImage(pImageId,cardId,val);
							});
							imgstate = "available";
					  }
				  }
			  });
		});

	}
	function saveQRCode(qrId, data){
		var el = $(".qrcode[element-id="+qrId+"]");
		var params = "";
		params += "elementId=" + qrId;
		params += "&top=" + el.css("top");
		params += "&left=" + el.css("left");
		params += "&data=" + encodeURIComponent(data);		
		params += "&width=" + el.css("width");
		params += "&height=" + el.css("height");
		params += "&rotation=" + el.attr("data-rotate");
		$.getJSON("card/process/processSaveQRCode.jsp?"+params, function(data){
			var items = [];
			  $.each(data, function(key, val) {
				  //do nothing
			  });
		});
	}
	function deleteImage(pImageId,cardId){
	  $('#img_div_' + pImageId).hide();
	  $('.img-holder[pimg-id="0"]').hide();
		var el = $('#img_div_' + pImageId).children(":first").children(":first");
		var params = "";
		params += "pimgId=" + pImageId;
		params += "&elementId=" + el.attr("element-id");
		params += "&cardId=" + cardId;
		$.getJSON("card/processDeleteImage.jsp?"+params, function(data){
			var items = [];
			  $.each(data, function(key, val) {
				  if (key == "result" &&  val=="success"){ 
					  $('#img_div_' + pImageId).remove();
					  $('.img-holder[pimg-id="0"]').remove();
					  $('.img-holder[pimg-id="'+pImageId+'"]').removeClass("active");
				  }
			  });
		});		
	}

	function createLogo(cardId, logotop, logoleft, logowidth, logoheight, logopath, logomoving, logoVisible, logocolor, elementId){
		var attrs = " logo-top='"+logotop+"' ";
		attrs +=  " logo-left='"+logoleft+"' ";
		attrs +=  " logo-width='"+logowidth+"' ";
		attrs +=  " logo-height='"+logoheight+"' ";
		attrs +=  " logo-path='"+logopath+"' ";
		attrs +=  " logo-moving='"+logomoving+"' ";
		attrs +=  " logo-visible='"+logoVisible+"' ";
		attrs +=  " element-id='"+elementId+"' ";
		attrs +=  " logo-color='"+logocolor+"' ";
		
		$("<div id='logo_div_" + elementId + "' class='picture  logo_div default-element' "+attrs+" style='z-index:" + 99 + "; top:"+logotop+"px; left:"+logoleft+"px;'><img class='dynamic' src='"+$("#hidden_path").val()+logopath+"' width='"+logowidth+"px' height='"+logoheight+"px' onload='onLogoLoad("+elementId+")'><div class='img-del-handler'><i class='icon-remove'></i></div><div>").appendTo($("#editable-area"));
		if (logomoving == 1){
			$('#logo_div_' + elementId).draggable( {
				"containment" :"parent"		
			});
		}

		$('#logo_div_' + elementId).hover(function(e) {
			$(this).find(".img-del-handler").each(function(){$(this).show();})
		}, function() {
			$(this).find(".img-del-handler").each(function(){$(this).hide();})
		});		
		$('#logo_div_' + elementId +" > .img-del-handler").click(function(){
			hideLogo(elementId);
		});
		$('#logo_div_' + elementId).on( "dragstop", function( event, ui ) {
			saveLogo(elementId);
		});
		var logodiv = "<div style='margin:0px auto; padding: 0px 10px;'>"+
		  "<div style='float: left; line-height: 28px; font-size: 12px; font-weight: bold; padding-top: 4px; padding-right: 5px;'>Renk Seç</div>"+
		  "<input type='hidden' class='simple_color' value='#"+logocolor+"'/>"+
		  "<div class='img-holder logo' style='margin-top:0px;'>"+
		  // SHOW BLUE LOGO BY DEFAULT
		  "<img src='"+$("#hidden_path").val()+$("#hidden_logo_0F3665").val()+"' class='img-polaroid' style='width:105px; height: 39px;'></div></div>";
		$("#images_tab_3").html(logodiv);
		$('.logo').attr("element-id",elementId);
		
		$(".logo").click(function(){
			if (!$(this).hasClass("active")){
				$(this).addClass("active");
				showLogo($(this).attr("element-id"));
			}
		});	
		if (logoVisible == "0"){
			hideLogo(elementId);
		}
		else{
			$('.logo').addClass("active");
		}
		$('.simple_color').css({"width":"20px","height":"20px"}).simpleColor({
		    border: '2px solid #FFFFFF',
		    buttonClass: 'button'
		});
		$(".simpleColorDisplay").css("background-color","#" + logocolor);
		var cardImg = $('#logo_div_' + elementId ).children(":first");
		$('#logo_div_' + elementId ).children(":first").on( "resizestop", function( event, ui ) {
			saveLogo(elementId);
		});
	}
	function onLogoLoad(elementId){
		var cardImg = $('#logo_div_' + elementId +" img");
		cardImg.resizable({
		      aspectRatio: cardImg.css("width").replace("px","")/cardImg.css("height").replace("px",""),
		      handles: 'se',
		      autoHide: true,
		      maxHeight: $("#editable-area").css("height").replace("px",""),
		      maxWidth: $("#editable-area").css("width").replace("px","")
	    });
	}
	function onLogoColorChanged(){
		$('.logo_div').attr("logo-color",$(".simple_color").val());
		$('.logo_div img').attr("src",$("#hidden_path").val()+$("#hidden_logo_"+$(".simple_color").val()).val());
		$('.logo_div').attr("logo-path",$("#hidden_logo_"+$(".simple_color").val()).val());
		saveLogo($('.logo_div').attr("element-id"));
	}
	function saveLogo(elementId){
		var el = $('#logo_div_' + elementId);
		var params = "";
		params += "elementId=" + el.attr("element-id");
		params += "&top=" + el.css("top");
		params += "&left=" + el.css("left");
		params += "&visible=" + el.attr("logo-visible");
		params += "&path=" + el.attr("logo-path");
		params += "&color=" + el.attr("logo-color");
		params += "&width=" + el.children(":first").css("width").replace("px","");
		params += "&height=" + el.children(":first").css("height").replace("px","");
		var hide = el.attr("logo-visible") == "0";
		$.getJSON("card/process/processSaveLogo.jsp?"+params, function(data){
			if (hide) 
				$('.logo').removeClass("active");
		});		
	}
	function hideLogo(elementId){
		$('#logo_div_' + elementId).attr("logo-visible","0").hide();
		saveLogo(elementId);
	}
	function showLogo(elementId){
		$('#logo_div_' + elementId).attr("logo-visible","1").show();
		$('#logo_div_' + elementId + " .ui-wrapper").css("height",$('#logo_div_' + elementId).attr("logo-height")+"px");
		$('#logo_div_' + elementId + " .ui-wrapper img").css("height",$('#logo_div_' + elementId).attr("logo-height")+"px");
		saveLogo(elementId);
	}

	function initColoredIcons(cardId){
		$(".iconColor").css({ opacity: 0.5 });
		$("#black-icons").css({ opacity: 1 });
		$("#white-icons").css({ opacity: 1 });
		$(".iconColor").hover(function(){
			if (!$(this).hasClass("selected"))
			{
				$(this).animate({opacity: 1.0},100);
			}
		},function(){
			if (!$(this).hasClass("selected"))
			{
				$(this).animate({ opacity: 0.5},100);
			}
		});
		$(".iconColor").click(function(){
			if(!$(this).hasClass("selected"))
			{
				$(".iconColor").removeClass("selected");
				$(this).addClass("selected");
				$(".iconColor").css({ opacity: 0.5});
				$(this).animate({ opacity: 1.0},100);
				$('.icons-tab').hide();
				$('#'+$(this).attr("data-target")).show();
				
			}
		});
		$('.fuskey-icon-container >  img').click(function(){
			createIcon(cardId, $(this).attr("src"), $(this).attr("data-path"));
		});
	}

	function createIcon(cardId,src, path){
		var icon_no = getNextIconNumber();

		$("<div id='icon_div_" + icon_no + "' class='picon default-element' icon-no='"+icon_no+"' style='z-index:" + 1 + ";'><img class='dynamic' src='"+src+"' icon-no='"+path+"' data-path='" + path + "'><div class='img-del-handler'><i class='icon-remove'></i></div><div>").appendTo($("#editable-area"));
		$('#icon_div_' + icon_no).draggable( {
			"containment" :"parent"		
		});
		$("#icon_div_" + icon_no).hover(function(e) {
			$(this).find(".img-del-handler").each(function(){$(this).show();})
		}, function() {
			$(this).find(".img-del-handler").each(function(){$(this).hide();})
		});		
		$("#icon_div_" + icon_no +" > .img-del-handler").click(function(){
			deleteIcon(icon_no,cardId);
		});
		saveIcon(icon_no,cardId,"-1");
	}
	
	function saveIcon(icon_no, cardId, elementId){
		var el = $('#icon_div_' + icon_no).children(":first");
		var params = "";
		params += "h=" + el.height();
		params += "&w=" + el.width();
		params += "&top=" + el.parent().position().top;
		params += "&left=" + el.parent().position().left;
		params += "&elementId=" + elementId;
		params += "&cardId=" + cardId;
		params += "&src=" + encodeURIComponent(el.attr("data-path"));
		
		$.getJSON("card/processSaveIcon.jsp?"+params, function(data){
			var items = [];
			  $.each(data, function(key, val) {
				  if (key == "element-id" &&  val!="-1"){ 
					  el.attr(key,val);
					  if (elementId == "-1"){
						  $('#icon_div_' + icon_no).attr("element-id",val)
							$('#icon_div_' + icon_no).on( "dragstop", function( event, ui ) {
								saveIcon(icon_no,cardId,val);
							});
					  }
				  }
			  });
		});		
	}
	function createExistingIcon(cardId,top,left,src,elementId,path){
		var icon_no = getNextIconNumber();
		$("<div id='icon_div_" + icon_no + "' element-id='"+elementId+"' class='picon default-element' icon-no='"+icon_no+"' style='z-index:" + 1 + "; top:"+top+"px; left:"+left+"px;'><img class='dynamic' src='"+src+"' icon-no='"+icon_no+"' data-path='"+path+"'><div class='img-del-handler'><i class='icon-remove'></i></div><div>").appendTo($("#editable-area"));
		$('#icon_div_' + icon_no).draggable( {
			"containment" :"parent"		
		});
		$("#icon_div_" + icon_no).hover(function(e) {
			$(this).find(".img-del-handler").each(function(){$(this).show();})
		}, function() {
			$(this).find(".img-del-handler").each(function(){$(this).hide();})
		});		
		$("#icon_div_" + icon_no +" > .img-del-handler").click(function(){
			deleteIcon(icon_no,cardId);
		});
		$('#icon_div_' + icon_no).on( "dragstop", function( event, ui ) {
			saveIcon(icon_no,cardId,elementId);
		});

	}

	function deleteIcon(icon_no,cardId){
	  $('#icon_div_' + icon_no).hide();
		var el = $('#icon_div_' + icon_no);
		var params = "";
		params += "elementId=" + el.attr("element-id");
		params += "&cardId=" + cardId;
		$.getJSON("card/processDeleteIcon.jsp?"+params, function(data){
			var items = [];
			  $.each(data, function(key, val) {
				  if (key == "result" &&  val=="success"){ 
					  $('#icon_div_' + icon_no).remove();
				  }
			  });
		});		
	}
	
	function toggleSnapToGrid(gridSize, bgFront, bgBack, gridFront, gridBack){
		if ($("#snapToGrid").prop("checked")){
			$(".ui-draggable").each(function(){
				var top = parseInt($(this).css("top").replace("px",""));
				var left = parseInt($(this).css("left").replace("px",""));
				top = gridSize * Math.round(top * 1.0 / gridSize);
				left = gridSize * Math.round(left * 1.0 / gridSize);
				$(this).css("top", top + "px").css("left", left + "px").draggable( "option", "grid", [ gridSize, gridSize ] );
				$(this).trigger('dragstop');
			});
			$("#canvas-front").css("background-image","url('" + fuskeyUrl + gridFront + "')");
			$("#canvas-back").css("background-image","url('" + fuskeyUrl + gridBack + "')");
		}
		else{
			$(".ui-draggable").each(function(){
				$(this).draggable( "option", "grid", [ 1, 1 ] );		
			});
			$("#canvas-front").css("background-image","url('" + fuskeyUrl + bgFront + "')");
			$("#canvas-back").css("background-image","url('" + fuskeyUrl + bgBack + "')");
		}
	}

	function bindSnapToGrid(gridSize, bgFront, bgBack, gridFront, gridBack){
		toggleSnapToGrid(gridSize, bgFront, bgBack, gridFront, gridBack);
		$("#snapToGrid").change(function(){
			toggleSnapToGrid(gridSize, bgFront, bgBack, gridFront, gridBack);
		});
	}